package com.soecode.lyf.controller;

import java.text.ParseException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.soecode.lyf.common.SessionBean;
import com.soecode.lyf.constant.Constants;
import com.soecode.lyf.entity.Dept;
import com.soecode.lyf.entity.Person;
import com.soecode.lyf.service.DeptService;
import com.soecode.lyf.service.PersonService;

/**
 * Created by lijie on 16/11/17.
 */
@Controller
@RequestMapping("/index")
public class IndexController {
	Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	PersonService userService;
	@Autowired
	DeptService deptService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView logon(HttpServletRequest request, Person person) throws ParseException {
		logger.info("login name{},pwd{}", person.getName(), person.getPwd());
		Person findPerson = userService.queryByNamePwd(person.getName(), person.getPwd());
		if (findPerson != null) {
			SessionBean sb = new SessionBean();
			sb.setPerson(findPerson);
			// sb.getPrivileges().add(findPerson.getRole());
			// SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
			// Date beginDate = new Date();
			// Calendar date = Calendar.getInstance();
			// date.setTime(beginDate);
			// date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
			// Date endDate = dft.parse(dft.format(date.getTime()));
			request.getSession().setAttribute(Constants.SESSION_BEAN, sb);

			List<Dept> deptList = deptService.queryAllDept();
			ModelAndView mad = new ModelAndView("inputInfo/personRecord");
			mad.addObject("deptList", deptList);
			return mad;
		}
		ModelAndView mad = new ModelAndView("redirect:/");
		return mad;
	}

	@RequestMapping("logout")
	public String logout(HttpServletRequest request) {
		Enumeration<String> em = request.getSession().getAttributeNames();
		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		request.getSession().invalidate();
		return "redirect:/";
	}

}
